﻿using AutoMapper;
using ManagementApi.Authorizers;
using ManagementApi.Models;
using ManagementApi.Models.Corp;
using ManagementApi.Models.Manage.ProjectGroup;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using ManagementApi.Mvc.Filters;
using ManagementApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Modules.Constructor;
using Modules.Corp;
using Modules.Device;
using Modules.Project;
using Newtonsoft.Json.Linq;
using PmSoft;
using PmSoft.Entity;
using PmSoft.Exceptions;
using System.Reflection.Emit;
using System.Security.Authentication;

namespace ManagementApi.Controllers.CorpPannel
{
    /// <summary>
    /// 常用业务接口-企业管理角色
    /// </summary>
    [Route("/api/v1/corp/common")]
    [ApiController]
    [Authorize(Roles = "Corp")]
    [TypeFilter(typeof(RequireSelProjectActionFilter))]
    public class CommonController : ControllerBase
    {
        private readonly CorpService corpService;
        private readonly ProjectGroupService projectGroupService;
        private readonly ProjectService projectService;
        private readonly CardReaderDeviceService sysDeviceService;
        private readonly CardReaderService cardReaderService;
        private readonly CorpApplicationContext applicationContext;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        public CommonController(CorpService corpService, CardReaderDeviceService sysDeviceService, CardReaderService cardReaderService, ProjectService projectService, ProjectGroupService projectGroupService, CorpApplicationContext applicationContext, IMapper mapper)
        {
            this.corpService = corpService;
            this.applicationContext = applicationContext;
            this.projectGroupService = projectGroupService;
            this.projectService = projectService;
            this.cardReaderService = cardReaderService;
            this.sysDeviceService = sysDeviceService;
            this.mapper = mapper;
        }

        /// <summary>
        /// 切换项目
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpPut("projectChanges/{projectId}")]
        public ApiResult ProjectChanges(int projectId)
        {
            #region 验证数据权限

            var projectInfo = projectService.GetProjectInfo(projectId);
            if (projectInfo == null)
                throw new BusinessException("项目不存在");

            if (projectInfo.LumpContractorCorpId != applicationContext.CurrentCorp.CorpId)//非总包企业需要验证是否为参建企业
            {
                var corpInfos = applicationContext.GetService<ProjectCorpService>().GetProjectCorpsByProjectId(projectId);

                if (!corpInfos.Any(s => s.CorpId == applicationContext.CurrentCorp.CorpId)) throw new OwnAuthorizationFailedException();
            }

            #endregion 验证数据权限

            corpService.UpdateDefaultProjectId(applicationContext.CurrentCorp, projectId);

            return ApiResult.Success("项目切换成功");
        }

        /// <summary>
        /// 班组下拉
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageNum"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("pulldown")]
        public ApiResult<PageDto<LabelValue<int>>> GetPullDown([FromQuery] ProjectGroupQuery query, int pageNum = 1, int pageSize = 9999)
        {
            query.ProjectId = applicationContext.CurrentProjectInfo.ProjectId;
            query.CorpId = applicationContext.CurrentCorp.CorpId;
            var data = projectGroupService.GetProjectGroups(query, pageNum, pageSize);
            var dtos = data.AsPageDto(source => { return source.AsPullDownDto(); });
            return ApiResult<PageDto<LabelValue<int>>>.Success(dtos);
        }

        /// <summary>
        /// 总包+分包企业查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("corps_manager")]
        public ApiResult<IEnumerable<CorpInfoDto>> GetManagerCorps()
        {
            if (!applicationContext.IsLumpContractorCorp())
            {
                List<CorpInfo> corps = new() { applicationContext.CurrentCorp };
                var dtos = corps.Select(m => m.AsDto(applicationContext));
                return ApiResult<IEnumerable<CorpInfoDto>>.Success(dtos);
            }
            else
            {
                var corpInfos = corpService.GetCorpsByProjectId(applicationContext.CurrentProjectInfo.ProjectId);
                var dtos = corpInfos.Select(m => m.AsDto(applicationContext));
                return ApiResult<IEnumerable<CorpInfoDto>>.Success(dtos);
            }
        }

        /// <summary>
        /// 获取当前登录企业角色
        /// </summary>
        /// <returns></returns>
        [HttpGet("projectCorpRole")]
        public ApiResult<string> GetProjectCorpRole()
        {
            var projectInfo = applicationContext.CurrentProjectInfo;

            if (applicationContext.CurrentUser is CorpInfo corpInfo && corpInfo.CorpId == projectInfo.LumpContractorCorpId)
                return ApiResult<string>.Success("工程总承包");
            if (applicationContext.CurrentUser is ConstructorInfo constructor && constructor.ConstructorId == projectInfo.BuildCorpId)
                return ApiResult<string>.Success("建设单位");

            var projectCorp = applicationContext.GetService<ProjectCorpService>().GetProjectCorpByProjectIdAndCorpId(projectInfo.ProjectId, applicationContext.CurrentCorp.CorpId);
            if (projectCorp == null)
                return ApiResult<string>.Success("未知");

            return ApiResult<string>.Success(projectCorp.Role.GetDescription("未知"));
        }

        #region 身份证阅读器

        /// <summary>
        /// 获取读卡器签名
        /// </summary>
        /// <returns></returns>
        //[HttpGet("getReadCardToken")]
        //public ApiResult<string> GetReadCardToken()
        //{
        //    string readId = Guid.NewGuid().ToString();

        // #region 查询项目的施工总包

        // var projectCorp =
        // projectCorpService.GetProjectCorpsByProjectId(applicationContext.CurrentProjectInfo.ProjectId).FirstOrDefault(a
        // => a.Role == 项目参建单位类型.总承包单位); if (projectCorp == null) return
        // ApiResult<string>.Failure("获取读卡器签名失败：当前登录项目没有总承包单位"); var corp =
        // corpService.GetCorpInfo(projectCorp.CorpId); if (corp == null) return ApiResult<string>.Failure("获取读卡器签名失败：当前登录项目总承包单位不存在");

        // #endregion 查询项目的施工总包

        //    string token = ReaderEncrypt.AESEncrypt($"{readId},{corp.Code}", isHex: true);
        //    return ApiResult<string>.Success(token);
        //}

        /// <summary>
        /// 同意接入读卡器
        /// </summary>
        /// <returns></returns>
		[HttpPut("confirmCardReader")]
        public ApiResult ConfirmCardReader()
        {
            #region 查询项目的施工总包

            var projectInfo = projectService.GetProjectInfo(applicationContext.CurrentProjectInfo.ProjectId);
            if (projectInfo == null) return ApiResult.Failure("当前登录项目不存在");
            var corp = corpService.GetCorpInfo(projectInfo.LumpContractorCorpId);
            if (corp == null) return ApiResult.Failure("获取读卡器签名失败：当前登录项目总承包单位不存在");

            #endregion 查询项目的施工总包

            var cardReaders = sysDeviceService.GetCardReaderDeviceByCorpCode(corp.Code);
            //筛选非待审核的读卡器，大于0则不允许自动审核
            if (cardReaders.Any(m => m.Status != 设备审核状态.待审核))
                return ApiResult.Failure("企业已接入了至少一个读卡器，接入多个需要联系管理员登记读卡器信息,联系电话：13398001090");

            //获取企业最新创建的一个待审核读卡器
            var cardReader = cardReaders.OrderByDescending(m => m.CreateTime).FirstOrDefault(m => m.Status == 设备审核状态.待审核);
            if (cardReader == null)
                return ApiResult.Failure("未获取到当前企业待登记读卡器信息");
            cardReader.Status = 设备审核状态.已审核;
            cardReader.AuditTime = DateTime.Now;
            cardReader.Description = "企业首个身份证读卡器自动登记";
            sysDeviceService.UpdateSysDevice(cardReader);
            return ApiResult.Success("读卡器接入成功");
        }

        #endregion 身份证阅读器
    }
}